import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login.vue'
import Home from '../components/home.vue'
import Welcome from '../components/welcome.vue'
import User from '../components/user/user.vue'
import Roles from '../components/rights/roles.vue'
import Rights from '../components/rights/rights.vue'
import Goods from '../components/goods/goods.vue'
import AddGoods from '../components/goods/addGoods.vue'
import Params from '../components/goods/params.vue'
import Categories from '../components/goods/categories.vue'
import Order from '../components/order/order.vue'
import Report from '../components/report/report.vue'

Vue.use(VueRouter)

const routes = [{
  path: '/login',
  component: Login
}, {
  path: '/',
  redirect: '/login'
}, {
  path: '/home',
  component: Home,
  redirect: '/welcome',
  children: [{
    path: '/welcome',
    component: Welcome
  }, {
    path: '/users',
    component: User
  }, {
    path: '/roles',
    component: Roles
  }, {
    path: '/rights',
    component: Rights
  }, {
    path: '/goods',
    component: Goods

  }, {
    path: '/params',
    component: Params
  }, {
    path: '/categories',
    component: Categories
  }, {
    path: '/addGoods',
    component: AddGoods
  }, {
    path: '/orders',
    component: Order
  }, {
    path: '/reports',
    component: Report
  }]
}]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 表示访问的路径， from表示从哪个路径跳转， next是一个函数表示跳转（next()直接放行， next('login)跳转到制定页面）
  if (to.path === '/login') {
    return next()
  }
  const token = window.localStorage.getItem('token')
  if (!token) {

    return next('/login')
  }
  return next()
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


export default router
